/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package InterfaceCliente;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import pbl_cliente.*;

/**
 *
 * @author tayane
 */
public class TelaConvidaUsuariosChat extends javax.swing.JFrame {

    /**
     * Creates new form TelaConvidaUsuariosChat
     */
    List<String> listaConexoesAtivas;
    Socket meuSocketLadoCliente;
    String meuEmail;
    int cont_convidados = 0;
    RecebeMsgChat recebeMsgs;
    PBL_cliente cliente;
    CotaChat cotaChat;
    
    DefaultListModel listaUsuariosChat = new DefaultListModel();
    DefaultListModel listaConvidadosChat = new DefaultListModel();
    
    public TelaConvidaUsuariosChat(List<String> conexoesAtivas, String meuEmail, PBL_cliente cli) {
        initComponents();
        setVisible(true);
        setLocationRelativeTo(null);
        this.listaConexoesAtivas = conexoesAtivas;
        this.meuEmail = meuEmail;
        this.cliente = cli;
        for(int i = 0; i < listaConexoesAtivas.size(); i++){
            //listaUsuariosChat.addElement(listaConexoesAtivas.get(i).split("#")[0] + " - " + listaConexoesAtivas.get(i).split("#")[1] );
            listaUsuariosChat.addElement(listaConexoesAtivas.get(i).split("#")[0]);
        }
        this.JlistUsuariosChat.setModel(listaUsuariosChat);
    }

    private TelaConvidaUsuariosChat() {
        //throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        JlistUsuariosChat = new javax.swing.JList();
        jButtonAddConvidado = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListConvidados = new javax.swing.JList();
        jButtonRemoveConvidado = new javax.swing.JButton();
        jButtonEnviarConvite = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        JlistUsuariosChat.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                JlistUsuariosChatMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(JlistUsuariosChat);

        jButtonAddConvidado.setText("Convidar =>");
        jButtonAddConvidado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddConvidadoActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel1.setText("Quais usuários você deseja convidar para o chat?");

        jScrollPane2.setViewportView(jListConvidados);

        jButtonRemoveConvidado.setText("Remover convidado");
        jButtonRemoveConvidado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoveConvidadoActionPerformed(evt);
            }
        });

        jButtonEnviarConvite.setFont(new java.awt.Font("Arial", 1, 11)); // NOI18N
        jButtonEnviarConvite.setText("ENVIAR CONVITE");
        jButtonEnviarConvite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEnviarConviteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButtonRemoveConvidado)
                .addGap(44, 44, 44))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonAddConvidado)
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(98, 98, 98))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jButtonEnviarConvite)
                                .addGap(212, 212, 212))))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(51, 51, 51)
                .addComponent(jLabel1)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonRemoveConvidado))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButtonAddConvidado)
                        .addGap(117, 117, 117)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jButtonEnviarConvite)
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAddConvidadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddConvidadoActionPerformed

        if(cont_convidados > 2){
            JOptionPane.showMessageDialog(rootPane, "Não é possível convidar mais de 2 usuários para o chat");            
        }
        else{
            if (!JlistUsuariosChat.isSelectionEmpty()){
                 String usuarioSelecionado = (String) JlistUsuariosChat.getSelectedValue();
                 //System.out.println("Usuario selecionado em UC: " + usuarioSelecionado);
                 listaConvidadosChat.addElement(usuarioSelecionado);
                 cont_convidados++;
                 listaUsuariosChat.remove(JlistUsuariosChat.getSelectedIndex());
                 JlistUsuariosChat.setModel(listaUsuariosChat);
                 jListConvidados.setModel(listaConvidadosChat);
            }
        }
             
    }//GEN-LAST:event_jButtonAddConvidadoActionPerformed

    private void JlistUsuariosChatMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JlistUsuariosChatMouseClicked

    }//GEN-LAST:event_JlistUsuariosChatMouseClicked

    private void jButtonEnviarConviteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEnviarConviteActionPerformed
         if(cont_convidados > 0){
            try {
                DataOutputStream solicitacaoCota = new DataOutputStream(this.cliente.getSocketCliente().getOutputStream());
                solicitacaoCota.writeUTF("RequisicaoCota");
                cotaChat = new CotaChat(this.cliente);
                this.cliente.decContChat();
                System.out.println("ContChat = " + cliente.getContChat());
                this.cotaChat.setDonoDaCota(true);
                new Thread(new Recebedor(this.cotaChat, this.cliente.getSocketCliente())).start();
            } catch (IOException ex) {
                Logger.getLogger(TelaConvidaUsuariosChat.class.getName()).log(Level.SEVERE, null, ex);
            }
             for(int i = 0; i < listaConvidadosChat.size(); i++){
                 String emailConvidado;
                 String ipConvidado;
                 int portaConvidado;               
                 for(int j = 0; j < listaConexoesAtivas.size(); j++){
                     if(listaConexoesAtivas.get(j).split("#")[0].equals(listaConvidadosChat.get(i))){
                         System.out.println("Convidado: " + listaConexoesAtivas.get(j).split("#")[0]);
                         System.out.println("ipConvidado: " + listaConexoesAtivas.get(j).split("#")[1]);
                         System.out.println("portaConvidado: " + listaConexoesAtivas.get(j).split("#")[2]);
                         emailConvidado = listaConexoesAtivas.get(j).split("#")[0];
                         ipConvidado = listaConexoesAtivas.get(j).split("#")[1];
                         portaConvidado = Integer.parseInt(listaConexoesAtivas.get(j).split("#")[2]);
                         
                         try {
                             this.meuSocketLadoCliente = new Socket(ipConvidado, portaConvidado);
                             this.cotaChat.addConvidado(this.meuSocketLadoCliente);
                             //chat = new ChatControl(meuEmail, cliente);
                             recebeMsgs = new RecebeMsgChat(this.cotaChat, meuSocketLadoCliente);
                             new Thread(recebeMsgs).start();
                         } catch (UnknownHostException ex) {
                             JOptionPane.showMessageDialog(rootPane, "UnknownHostException: Não foi possível enviar convite para " + emailConvidado);
                             Logger.getLogger(TelaConvidaUsuariosChat.class.getName()).log(Level.SEVERE, null, ex);
                         } catch (IOException ex) {
                             JOptionPane.showMessageDialog(rootPane, "IOException: Não foi possível enviar convite para " + emailConvidado);
                             Logger.getLogger(TelaConvidaUsuariosChat.class.getName()).log(Level.SEVERE, null, ex);
                         }
                     }
                     
                 }
                 
             }           
             this.dispose();
         }
         else{
             JOptionPane.showMessageDialog(rootPane, "Informe pelo menos 1 usuário para o envio do convite");
         }
    }//GEN-LAST:event_jButtonEnviarConviteActionPerformed

    private void jButtonRemoveConvidadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveConvidadoActionPerformed
            if (!jListConvidados.isSelectionEmpty()){
                cont_convidados--;
                String usuarioSelecionado = (String) jListConvidados.getSelectedValue();
                //System.out.println("Usuario selecionado CC: " + jListConvidados.getSelectedValue()); 
                listaConvidadosChat.remove(jListConvidados.getSelectedIndex());
                jListConvidados.setModel(listaConvidadosChat);
                listaUsuariosChat.addElement(usuarioSelecionado);
                System.out.println(usuarioSelecionado);
                JlistUsuariosChat.setModel(listaUsuariosChat);                 
            }
    }//GEN-LAST:event_jButtonRemoveConvidadoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaConvidaUsuariosChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaConvidaUsuariosChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaConvidaUsuariosChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaConvidaUsuariosChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaConvidaUsuariosChat().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList JlistUsuariosChat;
    private javax.swing.JButton jButtonAddConvidado;
    private javax.swing.JButton jButtonEnviarConvite;
    private javax.swing.JButton jButtonRemoveConvidado;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jListConvidados;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
